package com.tfswx.ruleengine.fn;

import com.greenpineyu.fel.context.FelContext;
import com.tfswx.ruleengine.compute.exception.AppException;
import com.tfswx.ruleengine.compute.gzjy.BaseFn;
import com.tfswx.ruleengine.compute.util.DateUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Ricky
 * @date 2021/4/29
 */
@Slf4j
public class SubDate extends BaseFn {
    private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");

    private static final String FORMAT_PATTERN = "yyyy-MM-dd";

    @Override
    public Object call(Object[] arguments, FelContext context) {
        String dateStr1 = String.valueOf(arguments[0]);
        String dateStr2 = String.valueOf(arguments[1]);

        Matcher matcher = DATE_PATTERN.matcher(dateStr1);
        if (!matcher.find()) {
            throw new AppException("dateStr1日期格式不满足2000-01-01的格式");
        }
        dateStr1 = matcher.group(1);

        matcher = DATE_PATTERN.matcher(dateStr2);
        if (!matcher.find()) {
            throw new AppException("dateStr2日期格式不满足2000-01-01的格式");
        }
        dateStr2 = matcher.group(1);

        long t = DateUtil.parse(dateStr1, FORMAT_PATTERN).getTime() - DateUtil.parse(dateStr2, FORMAT_PATTERN).getTime();

        return t / 1000 / 60 / 60 / 24;
    }

    @Override
    public String getZwmc() {
        return "计算两个日期间隔天数";
    }


    @Override
    public List<Param> getParams() {
        List<Param> params = new ArrayList<>();
        params.add(new Param("dateStr1"));
        params.add(new Param("dateStr2"));
        return params;
    }

    @Override
    public String getName() {
        return "subDate";
    }
}
